package main

import (
	"fmt"
	"net"
)

func handleConnection(conn net.Conn, conns *[]net.Conn) {
	defer conn.Close()
	fmt.Println("在等待客户端发信息" + conn.RemoteAddr().String())
	for {
		b := make([]byte, 1024)
		n, err := conn.Read(b)
		if n < 0 {
			continue
		}
		connsCopy := make([]net.Conn, 0, 10)
		copy(connsCopy, *conns)
		if err != nil {
			for i, item := range connsCopy {
				if item == conn {
					connsCopy = append(connsCopy[:i], connsCopy[i:]...)
					conns = &connsCopy
				}
			}
			fmt.Println("对话结束")
			fmt.Println(err)
			return
		}
		// for {
		// 	select {
		// 	case item := <-conns:
		// 		item.Write(b[:n])
		// 		fmt.Print(string(b[:n]))
		// 	}
		// }
		for _, item := range *conns {
			if item != conn {
				item.Write(b[:n])
			}
		}
		fmt.Print(string(b[:n]))
	}

}

func main() {
	fmt.Println("服务器开始监听")
	ln, err := net.Listen("tcp", "0.0.0.0:8920")
	if err != nil {
		// handle error
		fmt.Println("Listen监听出错")
		return
	}
	conns := make([]net.Conn, 0, 10)
	var conaddr *[]net.Conn
	// connsChan := make(chan net.Conn, 10)

	defer ln.Close()
	for {
		conn, err := ln.Accept()
		conns = append(conns, conn)
		conaddr = &conns
		// connsChan <- conn
		if err != nil {
			fmt.Println("connAccept监听出错")
			// handle error
			continue
		}
		go handleConnection(conn, conaddr)
	}
}
